package com.cn.event;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenyuncong on 2018/11/14.
 */
public class ReaderFile implements ApplicationListener<ContextRefreshedEvent> {

    public static Map<String,Integer> map = new HashMap<>();

    @Value("${common.path}")
    private String path;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try { // 防止文件建立或读取失败，用catch捕捉错误并打印，也可以throw

            /* 读入TXT文件 */
            String pathname = path; // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径
            File filename = new File(pathname); // 要读取以上路径的input。txt文件
            InputStreamReader reader = new InputStreamReader(
                    new FileInputStream(filename)); // 建立一个输入流对象reader
            BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
            String line = "";
            line = br.readLine();
            String [] parma = null;
            while (line != null) {
                line = br.readLine(); // 一次读入一行数据
                if(line!=null){
                    parma = line.split("-");
                    map.put(parma[0],Integer.parseInt(parma[1]));
                }
            }
            br.close();
            /* 写入Txt文件 */


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
